﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
using LanceCarol.Utility;

namespace CSI300Cons.CapitalDownloader
{
    public class CompositeIndex
    {
        /// <summary>
        /// 下载指数(当前沪深300的价格是)
        /// </summary>
        public double DownloadBI { get; set; }

        /// <summary>
        /// 计算指数：基数市值/基数市值*BI
        /// 计算指数=每天第k个计算市值/每天第一个计算市值*每天第一个下载指数数值
        /// </summary>
        public double CalculatedBI { get;set;}

        /// <summary>
        /// 基数市值(计算市值、新市值) = 求和[调整股本*新价格]
        /// </summary>
        public double RadixCapital { get; set; }

        public DateTime DownloadTime { get; set; }

        private const string CMD_Save = "INSERT INTO CompositeIndex([DownloadBI],[CalculatedBI],[RadixCapital],[DownloadTime]) values (@DownloadBI,@CalculatedBI,@RadixCapital,@DownloadTime)";
        private const string CMD_LoadFirstCI = "SELECT TOP 1 * FROM CompositeIndex WHERE DownloadTime>#{0}# ORDER BY DownloadTime ASC";

        public void Save()
        {
            OleDbParameter[] cmdParms = GetSaveParameters();
            cmdParms[0].Value = this.DownloadBI;
            cmdParms[1].Value = this.CalculatedBI;
            cmdParms[2].Value = this.RadixCapital;
            cmdParms[3].Value = this.DownloadTime;
            DbHelperOleDb.ExecuteSql(CMD_Save, cmdParms);
        }

        public static CompositeIndex LoadFirstCI(DateTime dateTime)
        {
            CompositeIndex result = null;

            using (OleDbDataReader reader = DbHelperOleDb.ExecuteReader(string.Format(CMD_LoadFirstCI,dateTime.Date.ToString("yyyy-MM-dd"))))
            {
                if (reader.Read())
                {
                    result = new CompositeIndex()
                    {
                        DownloadBI = Convert.ToDouble(reader[1]),
                        CalculatedBI = Convert.ToDouble(reader[2]),
                        RadixCapital =  Convert.ToDouble(reader[3]),
                        DownloadTime = reader.GetDateTime(4)
                    };
                }
            }
            return result;
        }

        private static OleDbParameter[] GetSaveParameters()
        {
            OleDbParameter[] parms = DbHelperOleDb.GetCachedParameters(CMD_Save);

            if (parms == null)
            {
                parms = new OleDbParameter[] {
                new OleDbParameter("@DownloadBI", OleDbType.Decimal), 
                new OleDbParameter("@CalculatedBI", OleDbType.Decimal), 
                new OleDbParameter("@RadixCapital", OleDbType.Decimal), 
                new OleDbParameter("@DownloadTime", OleDbType.Date) };

                DbHelperOleDb.CacheParameters(CMD_Save, parms);
            }

            return parms;
        }
    }
}
